package cn.enilu.flash.api.utils;

import cn.enilu.flash.utils.HttpUtil;
import cn.enilu.flash.utils.JsonUtil;
import cn.enilu.flash.utils.StringUtil;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;
@Component
public class BaiduMapUtils implements InitializingBean {
    @Value("${baidumap.iplocation.url}")
    private String url;
    @Value("${baidumap.iplocation.ak}")
    private String ak;
    @Value("${baidumap.iplocation.sk}")
    private String sk;
    @Value("${baidumap.iplocation.api}")
    private String api;

    public static String URL;
    public static String AK;
    public static String SK;
    public static String API;

    public static Map<String,Object> getAddress(String ip){
        Map paramsMap = new LinkedHashMap<String, String>();
        paramsMap.put("ak", AK);
        paramsMap.put("ip", ip);
        paramsMap.put("coor", "bd09ll");
        String sn = getSn(paramsMap,API,SK);
        if(StringUtil.isNotEmpty(sn)) {
            String newUrl = URL.replace("AK",AK).replace("IP", ip).replace("SN", sn);
            String s = HttpUtil.sendGet(newUrl, null);
            return JsonUtil.fromJson(Map.class, s);
        }
        return null;
    }

    public static Integer getCityCode(String ip){
        Map<String, Object> addressMap = getAddress(ip);
        Map<String,Object> contentMap = (Map<String, Object>) addressMap.get("content");
        Map<String,Object> addressDetailMap = (Map<String, Object>) contentMap.get("address_detail");
        return (Integer) addressDetailMap.get("city_code");
    }

    public static String getSn(Map<String,String> paramsMap,String api,String sk)  {
        try {
            String paramsStr = toQueryString(paramsMap);
            String wholeStr = new String(api + paramsStr + sk);
            String tempStr = URLEncoder.encode(wholeStr, "UTF-8");
            return MD5(tempStr);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
    // 对Map内所有value作utf8编码，拼接返回结果
    public static String toQueryString(Map<?, ?> data)
            throws UnsupportedEncodingException {
        StringBuffer queryString = new StringBuffer();
        for (Map.Entry<?, ?> pair : data.entrySet()) {
            queryString.append(pair.getKey() + "=");
            queryString.append(URLEncoder.encode((String) pair.getValue(),
                    "UTF-8") + "&");
        }
        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }
        return queryString.toString();
    }
    // 来自stackoverflow的MD5计算方法，调用了MessageDigest库函数，并把byte数组结果转换成16进制
    public static String MD5(String md5) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest
                    .getInstance("MD5");
            byte[] array = md.digest(md5.getBytes());
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
                        .substring(1, 3));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
        }
        return null;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        URL = url;
        API =api;
        AK = ak;
        SK = sk;
    }
}
